package org.zeqp.chatAI.aiterface.audio;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import com.baidu.aip.speech.AipSpeech;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

public class AuDioUtils {

    private String sss = "";
    private static final String APPID="47189883";
    private static final String ACCESS_KEY="8KTOq44NScoEc6NeiR2as8Yg";
    private static final String PRIVATE_KEY="7MxMN5P0w924iGe5GMrgIBTAU3mlwqip";


    public static String sendAudioData(byte[] binaryAudioData){
        AipSpeech speech = new AipSpeech(APPID,ACCESS_KEY,PRIVATE_KEY);
        speech.setConnectionTimeoutInMillis(2000);
        speech.setSocketTimeoutInMillis(60000);
        HashMap<String,Object> options = new HashMap<>();git
        options.put("dev_pid",1537);
        options.put("cuid", IdUtil.simpleUUID());
        String result = null;
        try {
            JSONObject pcm = speech.asr(binaryAudioData, "pcm", 16000, null);
            if(pcm.get("result")!=null){
                result = pcm.get("result").toString().replace('[',' ').trim();
                result = result.replace(']',' ').trim();
            }
            System.out.println(pcm.toString());
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "抱歉,我还不会回答这个问题";
        }

    }
    public static void sendAudioData(){
        AipSpeech speech = new AipSpeech(APPID,ACCESS_KEY,PRIVATE_KEY);
        speech.setConnectionTimeoutInMillis(2000);
        speech.setSocketTimeoutInMillis(60000);
        ClassLoader classLoader = AuDioUtils.class.getClassLoader();
        InputStream resourceAsStream = classLoader.getResourceAsStream("16k.wav");
        HashMap<String,Object> options = new HashMap<>();
        options.put("dev_pid",1537);
        options.put("cuid", IdUtil.simpleUUID());
        try {
            byte[] bytes = IoUtil.readBytes(resourceAsStream);
            JSONObject pcm = speech.asr(bytes, "pcm", 16000, options);
            System.out.println(pcm.toString());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            try {
                resourceAsStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }

}
